package com.ming_za.odupdaterserver.spring_modify;

import com.ming_za.odupdaterserver.core.config.ConfigManager;
import com.ming_za.odupdaterserver.core.service.account.AccountSQL;
import com.ming_za.odupdaterserver.core.utils.SnowflakeIdGenerator;
import com.ming_za.odupdaterserver.core.utils.account.AccountManager;
import com.ming_za.odupdaterserver.core.utils.account.impl.BinaryIncludeValidator;
import com.ming_za.odupdaterserver.core.utils.account.impl.JWTTokenFactory;
import com.ming_za.odupdaterserver.core.utils.account.impl.PasswordSHA256;
import com.ming_za.odupdaterserver.core.utils.account.param.TokenManager;
import com.ming_za.odupdaterserver.core.utils.account.preparatory.AccountType;
import com.ming_za.odupdaterserver.core.utils.account.preparatory.TokenType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Random;

@Component
public class OtherBean {

    private final ConfigManager configManager;
    private final AccountSQL accountSQL;

    public OtherBean(ConfigManager configManager, AccountSQL accountSQL) {
        this.configManager = configManager;
        this.accountSQL = accountSQL;
    }

    /**
     * 雪花算法bean注册
     */
    @Bean
    public SnowflakeIdGenerator snowflakeIdGenerator(){
        return new SnowflakeIdGenerator(
                configManager.getSnowflakeStartTimestamp().getValue(),
                configManager.getSnowflakeLastTimestamp().getValue(),
                configManager.getSnowflakeWorkerId().getValue(),
                configManager.getSnowflakeDatacenterId().getValue(),
                (lastTimestamp) -> configManager.getSnowflakeLastTimestamp().saveValue(lastTimestamp));
    }

    /**
     * 账号管理bean注册
     * <p>验证token时都检测ip</p>
     * <p>token有效时长2h，剩余30min续签</p>
     * <p></p>
     */
    @Bean
    public AccountManager accountManager(){
        return AccountManager.createAccountManager(AccountType.NORMAL_SINGLE_ACCOUNT,
                TokenManager.createTokenManager(new JWTTokenFactory(null, "odUpdater"), TokenType.BASE_WEB_TOKEN),
                new PasswordSHA256(), accountSQL, new BinaryIncludeValidator());
    }

    /**
     * 随机数
     */
    @Bean
    public Random random(){
        return new Random(System.currentTimeMillis());
    }

}
